<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>拖动元素示例</title>
    <style>
      body {
        height: 100vh;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #f0f0f0;
      }

      .draggable {
        width: 100px;
        height: 100px;
        background-color: #4caf50;
        color: white;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: grab;
        position: absolute;
      }
    </style>
  </head>
  <body>
    <div class="draggable">拖动我</div>

    <script>
      const draggable = document.querySelector(".draggable");
      let isDragging = false;
      let offsetX, offsetY;

      draggable.addEventListener("mousedown", function (event) {
        isDragging = true;
        offsetX = event.offsetX;
        offsetY = event.offsetY;
        draggable.style.cursor = "grabbing";
      });

      document.addEventListener("mousemove", function (event) {
        if (isDragging) {
          const x = event.clientX - offsetX;
          const y = event.clientY - offsetY;
          draggable.style.left = `${x}px`;
          draggable.style.top = `${y}px`;
        }
      });

      document.addEventListener("mouseup", function () {
        isDragging = false;
        draggable.style.cursor = "grab";
      });
    </script>
  </body>
</html>
